package cn.com.xyc.common;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QrCodeUtil {
	private static File addLogo(File qrCode, File logoImage) throws IOException {
		String imagePath = qrCode.getAbsolutePath();
		BufferedImage image = ImageIO.read(qrCode);
		File rqCodeImg = new File(imagePath);
		int logoWidth = image.getWidth() / 5; // 设置logo图片宽度为二维码图片的五分之一
		int logoHeight = image.getHeight() / 5; // 设置logo图片高度为二维码图片的五分之一
		int logoX = (image.getWidth() - logoWidth) / 2; // 设置logo图片的位置,这里令其居中
		int logoY = (image.getHeight() - logoHeight) / 2; // 设置logo图片的位置,这里令其居中
		Graphics2D graphics = image.createGraphics();
		graphics.drawImage(ImageIO.read(logoImage), logoX, logoY, logoWidth,
				logoHeight, null);
		graphics.dispose();
		ImageIO.write(image,
				imagePath.substring(imagePath.lastIndexOf(".") + 1), rqCodeImg);
		return rqCodeImg;
	}

	public static File encodeQRCodeImage(String content, String charset,
			int width, int height, File logoImage) {
		File folder = new File(ApplicationConstants.attachPath);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		File qrCode = new File(ApplicationConstants.attachPath
				+ System.currentTimeMillis()+".png");
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		BitMatrix bitMatrix = null;
		try {
			bitMatrix = new MultiFormatWriter().encode(
					new String(content.getBytes(charset == null ? "UTF-8"
							: charset), "ISO-8859-1"), BarcodeFormat.QR_CODE,
					width, height, hints);
		} catch (Exception e) {
			logger.error("编码待生成二维码图片的文本时发生异常,堆栈轨迹如下");
		}
		MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001,
				0xFFFFFFFF);
		try {
			MatrixToImageWriter.writeToFile(bitMatrix, "png", qrCode, config);
		} catch (IOException e) {
			logger.error("生成二维码图片时遇到异常,堆栈轨迹如下");
		}
		if (logoImage != null) {
			try {
				addLogo(qrCode, logoImage);
			} catch (IOException e) {
				logger.error("为二维码图片添加logo头像[" + logoImage.getName()
						+ "]时遇到异常,堆栈轨迹如下");
				e.printStackTrace();
			}
		}
		return qrCode;
	}

	final static Logger logger = LoggerFactory.getLogger(QrCodeUtil.class);
}
